import React, { useMemo } from 'react';
import { 
  Card, 
  Spin, 
  Typography, 
  Space,
  Alert,
  message
} from 'antd';
import {
  BugOutlined,
  InfoCircleOutlined,
  CheckCircleOutlined,
  PlayCircleOutlined
} from '@ant-design/icons';
import { useAnalysisContext, useAnalysisActions } from '../../context/AnalysisContext';
import EnhancedProblemTable from './EnhancedProblemTable';
import { UnifiedProblemData } from '../../types/analysis';
import { convertLegacyProblemsToUnified } from '../../utils/problemDataConverter';
import './AnalysisResults.css';

const { Text } = Typography;

const UnifiedRuleAnalysisResults: React.FC = () => {
  const { state } = useAnalysisContext();
  const actions = useAnalysisActions();

  const {
    analysisResult,
    isAnalyzing,
    sqlContent,
    sourceDbType,
    targetDbType,
    selectedIssueId
  } = state;

  // 生成统一的问题数据
  const unifiedProblems = useMemo((): UnifiedProblemData[] => {
    if (!analysisResult?.issues) return [];

    // 将规则分析结果分组
    const groupedIssues = [
      {
        key: 'HIGH',
        title: '高危问题',
        icon: <BugOutlined style={{ color: '#ff4d4f' }} />,
        count: analysisResult.issues.filter(i => i.severity === 'HIGH').length,
        items: analysisResult.issues.filter(i => i.severity === 'HIGH').map(issue => ({
          id: issue.id,
          lineNumber: issue.lineNumber,
          columnNumber: issue.columnNumber,
          severity: issue.severity as any,
          category: issue.category,
          description: issue.description,
          suggestion: issue.suggestion,
          ruleName: issue.ruleName,
          originalCode: issue.originalCode,
          suggestedCode: issue.suggestedCode,
          sqlFragment: issue.sqlFragment
        })),
        color: '#ff4d4f'
      },
      {
        key: 'MEDIUM',
        title: '中危问题',
        icon: <BugOutlined style={{ color: '#faad14' }} />,
        count: analysisResult.issues.filter(i => i.severity === 'MEDIUM').length,
        items: analysisResult.issues.filter(i => i.severity === 'MEDIUM').map(issue => ({
          id: issue.id,
          lineNumber: issue.lineNumber,
          columnNumber: issue.columnNumber,
          severity: issue.severity as any,
          category: issue.category,
          description: issue.description,
          suggestion: issue.suggestion,
          ruleName: issue.ruleName,
          originalCode: issue.originalCode,
          suggestedCode: issue.suggestedCode,
          sqlFragment: issue.sqlFragment
        })),
        color: '#faad14'
      },
      {
        key: 'LOW',
        title: '低危问题',
        icon: <InfoCircleOutlined style={{ color: '#1890ff' }} />,
        count: analysisResult.issues.filter(i => i.severity === 'LOW').length,
        items: analysisResult.issues.filter(i => i.severity === 'LOW').map(issue => ({
          id: issue.id,
          lineNumber: issue.lineNumber,
          columnNumber: issue.columnNumber,
          severity: issue.severity as any,
          category: issue.category,
          description: issue.description,
          suggestion: issue.suggestion,
          ruleName: issue.ruleName,
          originalCode: issue.originalCode,
          suggestedCode: issue.suggestedCode,
          sqlFragment: issue.sqlFragment
        })),
        color: '#1890ff'
      },
      {
        key: 'INFO',
        title: '提示信息',
        icon: <InfoCircleOutlined style={{ color: '#52c41a' }} />,
        count: analysisResult.issues.filter(i => i.severity === 'INFO').length,
        items: analysisResult.issues.filter(i => i.severity === 'INFO').map(issue => ({
          id: issue.id,
          lineNumber: issue.lineNumber,
          columnNumber: issue.columnNumber,
          severity: issue.severity as any,
          category: issue.category,
          description: issue.description,
          suggestion: issue.suggestion,
          ruleName: issue.ruleName,
          originalCode: issue.originalCode,
          suggestedCode: issue.suggestedCode,
          sqlFragment: issue.sqlFragment
        })),
        color: '#52c41a'
      }
    ].filter(group => group.count > 0);

    return convertLegacyProblemsToUnified(groupedIssues, 'RULE');
  }, [analysisResult]);

  // 计算统计数据
  const statistics = useMemo(() => {
    if (!analysisResult?.statistics) return null;
    
    const stats = analysisResult.statistics;
    return {
      total: stats.totalIssues || 0,
      high: stats.highSeverityCount || 0,
      medium: stats.mediumSeverityCount || 0,
      low: stats.lowSeverityCount || 0,
      info: stats.infoCount || 0,
      categories: {
        syntax: stats.categoryCounts?.SYNTAX || 0,
        function: stats.categoryCounts?.FUNCTION || 0,
        datatype: stats.categoryCounts?.DATATYPE || 0,
        performance: stats.categoryCounts?.PERFORMANCE || 0
      }
    };
  }, [analysisResult]);

  // 处理问题点击
  const handleIssueClick = (issue: UnifiedProblemData) => {
    actions.setSelectedIssueId(issue.id);
    actions.setCursorPosition({ 
      line: issue.lineNumber, 
      column: issue.columnNumber 
    });
  };

  // 处理应用建议
  const handleApplySuggestion = (issue: UnifiedProblemData) => {
    if (!issue.suggestedCode) {
      message.warning('该问题没有优化建议');
      return;
    }

    // 实现将建议应用到编辑器的逻辑
    const newSqlContent = sqlContent.replace(
      issue.originalCode || issue.sqlFragment || '',
      issue.suggestedCode
    );
    
    actions.setSqlContent(newSqlContent);
    message.success(`已应用${issue.ruleName}的优化建议`);
  };

  // 处理批量应用
  const handleBatchApply = (issues: UnifiedProblemData[]) => {
    let newSqlContent = sqlContent;
    
    // 按SQL语句编号排序，确保正确的应用顺序
    const sortedIssues = [...issues].sort((a, b) => a.statementNumber - b.statementNumber);
    
    sortedIssues.forEach(issue => {
      if (issue.suggestedCode && (issue.originalCode || issue.sqlFragment)) {
        newSqlContent = newSqlContent.replace(
          issue.originalCode || issue.sqlFragment || '',
          issue.suggestedCode
        );
      }
    });
    
    actions.setSqlContent(newSqlContent);
    message.success(`已批量应用 ${issues.length} 个优化建议`);
  };

  // 渲染空状态
  const renderEmptyState = () => {
    if (!sqlContent.trim()) {
      return (
        <div className="analysis-empty">
          <div className="analysis-empty-icon">
            <BugOutlined />
          </div>
          <div className="analysis-empty-text">
            请在左侧编辑器中输入SQL语句
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            支持Oracle、MySQL、PostgreSQL等多种数据库
          </Text>
        </div>
      );
    }

    if (sourceDbType === targetDbType) {
      return (
        <div className="analysis-empty">
          <div className="analysis-empty-icon">
            <InfoCircleOutlined />
          </div>
          <div className="analysis-empty-text">
            源数据库和目标数据库相同
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            请选择不同的数据库类型进行兼容性分析
          </Text>
        </div>
      );
    }

    return (
      <div className="analysis-empty">
        <div className="analysis-empty-icon">
          <PlayCircleOutlined />
        </div>
        <div className="analysis-empty-text">
          点击"规则分析"按钮开始分析
        </div>
        <Text type="secondary" style={{ fontSize: '12px' }}>
          基于预定义规则检测兼容性问题
        </Text>
      </div>
    );
  };

  // 渲染成功状态
  const renderSuccessState = () => (
    <div className="analysis-empty">
      <div className="analysis-empty-icon" style={{ color: '#52c41a' }}>
        <CheckCircleOutlined />
      </div>
      <div className="analysis-empty-text">
        恭喜！未发现兼容性问题
      </div>
      <Text type="secondary" style={{ fontSize: '12px' }}>
        您的SQL语句可以直接在目标数据库中使用
      </Text>
    </div>
  );

  return (
    <Card 
      className="results-section rule-analysis-results"
      title={
        <Space>
          <BugOutlined />
          <span>规则分析结果</span>
          {isAnalyzing && <Spin size="small" />}
        </Space>
      }
      size="small"
    >
      {isAnalyzing ? (
        <div className="analysis-loading">
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>
            <Text>正在进行规则分析...</Text>
          </div>
        </div>
      ) : unifiedProblems.length > 0 ? (
        <div>
          {statistics && statistics.total > 0 && (
            <Alert
              message={`发现 ${statistics.total} 个兼容性问题`}
              description={`其中高危问题 ${statistics.high} 个，中危问题 ${statistics.medium} 个，建议及时处理`}
              type={statistics.high > 0 ? 'error' : statistics.medium > 0 ? 'warning' : 'info'}
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}
          
          <EnhancedProblemTable
            problems={unifiedProblems}
            selectedIssueId={selectedIssueId}
            onIssueClick={handleIssueClick}
            onApplySuggestion={handleApplySuggestion}
            onBatchApply={handleBatchApply}
            height={600}
            taskConfig={{ taskType: 'MANUAL_SQL' }} // 手动SQL分析默认配置
          />
        </div>
      ) : (
        analysisResult ? renderSuccessState() : renderEmptyState()
      )}
    </Card>
  );
};

export default UnifiedRuleAnalysisResults;